<template>
	<tm-app>
		<tm-sheet :margin="[24, 24]">
			<tm-input v-model="newProductName" placeholder="输入新产品名称" :shadow="2" :round="25"></tm-input>
			<tm-button @click="addProduct" :shadow="2" :round="25" block class="mt-20">添加产品</tm-button>
		</tm-sheet>

		<tm-sheet :margin="[24, 24]">
			<tm-text :font-size="32" class="text-weight-b" label="产品列表"></tm-text>
			<view v-if="store.products.length === 0" class="flex-center pa-24">
				<tm-text color="grey" label="暂无产品，请先添加"></tm-text>
			</view>
			<view v-for="product in store.products" :key="product.id">
				<tm-sheet :margin="[0, 12]" :padding="[12, 12]">
					<view class="flex flex-row flex-between items-center" style="width: 100%">
						<view @click="goToProduct(product.id)" class="flex-1 mr-20">
							<tm-text :font-size="30" class="text-weight-b" :label="product.name"></tm-text>
							<tm-money fontSize="28" preFontSize="24" symbolText="成本价: ￥" :modelValue="product.totalPrice" :digit="2"></tm-money>
						</view>
						<tm-button @click="promptDelete(product.id)" color="error" size="s">删除</tm-button>
					</view>
				</tm-sheet>
			</view>
		</tm-sheet>

		<tm-modal v-model:show="showDeleteModal" title="确认删除" @confirm="confirmDelete">
			<tm-text>确定要删除此产品吗？</tm-text>
		</tm-modal>
	</tm-app>
</template>
<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useProductStore } from '../../store/product'

const store = useProductStore()
const newProductName = ref('')
const showDeleteModal = ref(false)
const productToDelete = ref(null)

function addProduct() {
	if (newProductName.value.trim()) {
		store.addProduct(newProductName.value.trim())
		newProductName.value = ''
	}
}

function goToProduct(id) {
	uni.navigateTo({ url: `/pages/product/index?id=${id}` })
}

function promptDelete(id) {
	productToDelete.value = id
	showDeleteModal.value = true
}

function confirmDelete() {
	if (productToDelete.value !== null) {
		store.deleteProduct(productToDelete.value)
		productToDelete.value = null
		showDeleteModal.value = false // 关闭弹窗
	}
}

onShow(() => {
	// 强制每次进入页面时都从本地存储重新加载数据，确保列表最新
	store.load()
})
</script>
<style lang="scss" scoped></style>
